package cn.iocoder.yudao.module.product.service.calculation;

import cn.iocoder.yudao.module.product.controller.admin.calculation.vo.ProcessCalculationCreateReqVO;
import cn.iocoder.yudao.module.product.controller.admin.calculation.vo.ProcessCalculationUpdateReqVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.module.product.dal.dataobject.calculation.ProcessCalculationDO;

import cn.iocoder.yudao.module.product.convert.calculation.ProcessCalculationConvert;
import cn.iocoder.yudao.module.product.dal.mysql.calculation.ProcessCalculationMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.*;

/**
 * 工序-核算关联 Service 实现类
 *
 * @author wcl
 */
@Service
@Validated
public class ProcessCalculationServiceImpl implements ProcessCalculationService {

    @Resource
    private ProcessCalculationMapper processCalculationMapper;

    @Override
    public Long createProcessCalculation(ProcessCalculationCreateReqVO createReqVO) {
        // 插入
        ProcessCalculationDO processCalculation = ProcessCalculationConvert.INSTANCE.convert(createReqVO);
        QueryWrapper<ProcessCalculationDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("process_id", createReqVO.getProcessId())
                    .eq("calculation_id", createReqVO.getCalculationId());
        ProcessCalculationDO processCalculationFlag = processCalculationMapper.selectOne(queryWrapper);
        if (processCalculationFlag != null){
            processCalculationMapper.update(processCalculation, queryWrapper);
        }else{
            processCalculationMapper.insert(processCalculation);
        }
        // 返回
        return processCalculation.getId();
    }

    @Override
    public void updateProcessCalculation(ProcessCalculationUpdateReqVO updateReqVO) {
        // 校验存在
        validateProcessCalculationExists(updateReqVO.getId());
        // 更新
        ProcessCalculationDO updateObj = ProcessCalculationConvert.INSTANCE.convert(updateReqVO);
        processCalculationMapper.updateById(updateObj);
    }

    @Override
    public void deleteProcessCalculation(Long id) {
        // 校验存在
        validateProcessCalculationExists(id);
        // 删除
        processCalculationMapper.deleteById(id);
    }

    private void validateProcessCalculationExists(Long id) {
        if (processCalculationMapper.selectById(id) == null) {
            throw exception(PROCESS_CALCULATION_NOT_EXISTS);
        }
    }

    @Override
    public ProcessCalculationDO getProcessCalculation(Long id) {
        return processCalculationMapper.selectById(id);
    }

}
